package com.lojzes.minwebserver;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
public class Processor extends Thread {
	private InputStream in = null;
	private PrintStream out = null;
    private static String WEB_ROOT="";
	public Processor(Socket socket,String webRoot) {
		try {
			WEB_ROOT = webRoot;
			in = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		String fileName = parse(in);
		sendContent(fileName);
	}
	
	public String parse(InputStream in){
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
		String fileName = "";
		try {
			String httpHead = bufferedReader.readLine();
			String[] content = httpHead.split(" ");
			if(content.length!=3){
				sendErrorMsg(400,"Clinet query error!");
				return null;
			}
			fileName = content[1];
			System.out.println("method:"+content[0]+" fileName:"+content[1]+" version:"+content[2]);
		} catch (IOException e) {
			e.printStackTrace();
			try {
				out.close();
				in.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} 
		
		return fileName;
	}
	
	public void sendContent(String fileName){
		if(null == fileName || (null != fileName && fileName.length()==0)){
			System.out.println("fileName error==>>"+fileName);
			return;
		}
		System.out.println("file path:"+WEB_ROOT+fileName);
		File file = new File(WEB_ROOT+fileName);
		if(!file.exists()){
			sendErrorMsg(404,"File Not Found!");
			return;
		}
		byte[] fileBytes = new byte[(int) file.length()];
		FileInputStream fileInputStream=null;
		try {
			fileInputStream = new FileInputStream(file);
			fileInputStream.read(fileBytes);
			out.println("HTTP/1.1 200 file query");
			out.println("content-length:"+fileBytes.length);
			out.println();
			out.write(fileBytes);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				out.flush();
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	public void sendErrorMsg(int errorCode,String msg){
		 out.println("HTTP/1.1 "+errorCode+" "+msg);
		 out.println("content-type: text/html");
		 out.println();
		 out.println("<html>");
		 out.println("<title> ERROR MSG");
		 out.println("</title>");
		 out.println("<body>");
		 out.println("<h1> errorCode:"+errorCode+" msg:"+msg);
		 out.println("</h1>");
		 out.println("</body>");
		 out.println("</html>");
		 try {
			out.flush();
			out.close();
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
